package hrx.service;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class FileUploadService {

    public Map<String, Object> validateFile(MultipartFile file) {
        Map<String, Object> result = new HashMap<>();

        if (file.isEmpty()) {
            result.put("success", false);
            result.put("message", "文件不能为空");
            return result;
        }

        // 文件大小验证
        long maxSize = 5 * 1024 * 1024; // 5MB
        if (file.getSize() > maxSize) {
            result.put("success", false);
            result.put("message", "文件大小不能超过5MB");
            return result;
        }

        // 文件类型验证
        String contentType = file.getContentType();
        if (!isImageContentType(contentType)) {
            result.put("success", false);
            result.put("message", "只支持图片文件");
            return result;
        }

        result.put("success", true);
        return result;
    }

    private boolean isImageContentType(String contentType) {
        return contentType != null && contentType.startsWith("image/");
    }

    public String saveFile(MultipartFile file, String uploadPath) throws IOException {
        // 创建目录
        File dir = new File(uploadPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 生成文件名
        String fileName = generateFileName(file.getOriginalFilename());
        String filePath = uploadPath + File.separator + fileName;

        // 保存文件
        file.transferTo(new File(filePath));

        return fileName;
    }

    private String generateFileName(String originalFileName) {
        String extension = originalFileName.substring(originalFileName.lastIndexOf("."));
        return System.currentTimeMillis() + "_" + UUID.randomUUID().toString().substring(0, 8) + extension;
    }
}
